<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <el-page-header @back="$router.push('/dashboard')" style="margin-bottom: 20px;">
        <template #content>
          <span style="font-size: 18px; font-weight: 600;">Create Recharge Order</span>
        </template>
      </el-page-header>
    </div>

    <!-- 主要内容 -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- 订单创建表单 -->
        <el-col :span="16">
          <el-card shadow="hover">
            <template #header>
              <div style="display: flex; align-items: center; justify-content: space-between;">
                <span style="font-size: 16px; font-weight: 600;">Create Recharge Order</span>
                <el-tag type="info">Please fill in complete information</el-tag>
              </div>
            </template>

            <el-form
              ref="orderFormRef"
              :model="orderForm"
              :rules="orderRules"
              label-width="140px"
              style="max-width: 600px;"
            >
              <!-- Payment Channel Selection -->
              <el-form-item label="Payment Channel" prop="paymentChannel">
                <el-select
                  v-model="orderForm.paymentChannel"
                  placeholder="Please select a payment channel manually"
                  style="width: 100%;"
                  @change="handleChannelChange"
                >
                  <el-option
                    v-for="channel in availableChannels"
                    :key="channel.value"
                    :label="channel.label"
                    :value="channel.value"
                  />
                </el-select>
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  Please manually select the payment channel for this order
                </div>
              </el-form-item>

              <!-- Payment Method Selection -->
              <el-form-item label="Payment Method" prop="paymentMethod">
                <el-select v-model="orderForm.paymentMethod" placeholder="Please select payment method" style="width: 100%;">
                  <el-option label="Bank Transfer" value="BankTransfer" />
                  <el-option label="QR Code Payment" value="qrPay" />
                </el-select>
              </el-form-item>

              <!-- UID -->
              <el-form-item label="User UID" prop="userId">
                <el-input-number
                  v-model="orderForm.userId"
                  :min="1"
                  placeholder="Please enter user UID"
                  style="width: 100%;"
                  controls-position="right"
                />
              </el-form-item>

              <!-- Recharge Amount -->
              <el-form-item label="Recharge Amount" prop="amount">
                <el-input-number
                  v-model="orderForm.amount"
                  :min="1"
                  :max="100000"
                  :precision="2"
                  placeholder="Please enter recharge amount"
                  style="width: 100%;"
                  controls-position="right"
                />
              </el-form-item>

              <!-- Payer Name - Required by TopPay -->
              <el-form-item label="Payer Name" prop="paymentName">
                <el-input
                  v-model="orderForm.paymentName"
                  placeholder="Please enter payer's real name"
                  style="width: 100%;"
                  maxlength="50"
                  show-word-limit
                />
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  Please enter real name for payment verification
                </div>
              </el-form-item>

              <!-- Bank Card Number - Required for all payment methods -->
              <el-form-item
                label="Bank Card Number"
                prop="transAccNo"
              >
                <el-input
                  v-model="orderForm.transAccNo"
                  placeholder="Please enter bank card number"
                  style="width: 100%;"
                  maxlength="20"
                  show-word-limit
                />
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  Please provide real bank card number for payment verification
                </div>
              </el-form-item>

              <!-- Bank Code - Required for all payment methods except LSPPAY -->
              <el-form-item
                :label="orderForm.paymentChannel === 'LSPPAY' ? 'Bank Code (Optional)' : 'Bank Code'"
                prop="bankCode"
              >
                <el-select
                  v-model="orderForm.bankCode"
                  :placeholder="orderForm.paymentChannel === 'LSPPAY' ? 'Optional for LSPPAY' : 'Please select bank'"
                  style="width: 100%;"
                  filterable
                  :allow-create="orderForm.paymentChannel === 'HUIFENG'"
                >
                  <el-option 
                    v-for="bank in bankOptions" 
                    :key="bank.value" 
                    :label="bank.label" 
                    :value="bank.value" 
                  />
                </el-select>
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  {{ orderForm.paymentChannel === 'LSPPAY' 
                    ? 'LSPPAY uses PromptPay by default, bank code is optional' 
                    : 'Selecting the corresponding bank can improve payment success rate' }}
                </div>
              </el-form-item>

              <!-- Customer Email - Optional -->
              <el-form-item label="Customer Email" prop="customerEmail">
                <el-input
                  v-model="orderForm.customerEmail"
                  placeholder="Please enter customer email (optional)"
                  style="width: 100%;"
                  maxlength="64"
                  show-word-limit
                />
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  Default email will be used if not provided
                </div>
              </el-form-item>

              <!-- Customer Phone - Optional -->
              <el-form-item label="Customer Phone" prop="customerPhone">
                <el-input
                  v-model="orderForm.customerPhone"
                  placeholder="Please enter customer phone (optional)"
                  style="width: 100%;"
                  maxlength="20"
                  show-word-limit
                />
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  Default phone number will be used if not provided
                </div>
              </el-form-item>

              <!-- Remarks -->
              <el-form-item label="Remarks" prop="extendParam">
                <el-input
                  v-model="orderForm.extendParam"
                  type="textarea"
                  :rows="3"
                  placeholder="Please enter remarks (optional)"
                  style="width: 100%;"
                  maxlength="100"
                  show-word-limit
                />
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  Remarks will be returned after order completion
                </div>
              </el-form-item>

              <!-- Order Creator -->
              <el-form-item label="Order Creator" prop="createdByName">
                <el-input
                  v-model="orderForm.createdByName"
                  placeholder="Please enter order creator name"
                  style="width: 100%;"
                  maxlength="50"
                  show-word-limit
                />
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  Enter the name of the customer service representative creating this order
                </div>
              </el-form-item>

              <!-- Action Buttons -->
              <el-form-item>
                <el-button type="primary" @click="handleCreateOrder" :loading="creating">
                  <el-icon><Plus /></el-icon>
                  Create Order
                </el-button>
                <el-button @click="handleResetForm">
                  <el-icon><Refresh /></el-icon>
                  Reset Form
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- Order Preview -->
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <span style="font-size: 16px; font-weight: 600;">Order Preview</span>
            </template>

            <div v-if="orderForm.userId && orderForm.amount && orderForm.paymentName && orderForm.paymentChannel" class="order-preview">
              <el-descriptions :column="1" border size="small">
                <el-descriptions-item label="Payment Channel">{{ paymentChannelLabel }}</el-descriptions-item>
                <el-descriptions-item label="Payment Method">{{ paymentMethodLabel }}</el-descriptions-item>
                <el-descriptions-item label="User UID">{{ orderForm.userId }}</el-descriptions-item>
                <el-descriptions-item label="Payer Name">{{ orderForm.paymentName }}</el-descriptions-item>
                <el-descriptions-item label="Recharge Amount">
                  <span style="color: #f56c6c; font-weight: 600;">
                    ¥{{ orderForm.amount }}
                  </span>
                </el-descriptions-item>
                <el-descriptions-item
                  v-if="orderForm.transAccNo"
                  label="Bank Card Number"
                >
                  {{ orderForm.transAccNo }}
                </el-descriptions-item>
                <el-descriptions-item
                  v-if="orderForm.bankCode"
                  label="Bank"
                >
                  {{ getBankLabel(orderForm.bankCode) }}
                </el-descriptions-item>
                <el-descriptions-item
                  v-if="orderForm.customerEmail"
                  label="Customer Email"
                >
                  {{ orderForm.customerEmail }}
                </el-descriptions-item>
                <el-descriptions-item
                  v-if="orderForm.customerPhone"
                  label="Customer Phone"
                >
                  {{ orderForm.customerPhone }}
                </el-descriptions-item>
                <el-descriptions-item
                  v-if="orderForm.extendParam"
                  label="Remarks"
                >
                  {{ orderForm.extendParam }}
                </el-descriptions-item>
                <el-descriptions-item label="Order Creator">{{ orderForm.createdByName }}</el-descriptions-item>
              </el-descriptions>

              <div style="margin-top: 20px; padding: 16px; background-color: #f5f7fa; border-radius: 4px;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <span style="font-weight: 600;">Recharge Amount:</span>
                  <span style="font-size: 18px; color: #f56c6c; font-weight: 600;">
                    ¥{{ orderForm.amount }}
                  </span>
                </div>
              </div>
            </div>

            <div v-else class="empty-preview">
              <el-empty description="Please fill in complete information" :image-size="80" />
            </div>
          </el-card>


        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useToast } from 'vue-toastification'
import { Plus, Refresh } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { trpc } from '../utils/trpc'
import { useAuthStore } from '../stores/auth'

// 响应式数据
const orderFormRef = ref<FormInstance>()
const creating = ref(false)
const authStore = useAuthStore()
const availableChannels = ref<Array<{value: string, label: string}>>([])
const loading = ref(false)

// 表单数据
const orderForm = ref({
  paymentChannel: '', // 支付渠道
  paymentMethod: '', // 支付方式
  userId: null as number | null,
  amount: null as number | null,
  transAccNo: '', // 银行卡号
  paymentName: '', // 付款人姓名（必填）
  bankCode: '', // 银行编码
  customerEmail: '', // 客户邮箱（可选）
  customerPhone: '', // 客户手机号（可选）
  extendParam: '', // 备注信息
  createdByName: '', // 开单客服名称
})

// Form validation rules
const orderRules = computed<FormRules>(() => ({
  paymentChannel: [
    { required: true, message: 'Please select payment channel', trigger: 'change' }
  ],
  paymentMethod: [
    { required: true, message: 'Please select payment method', trigger: 'change' }
  ],
  userId: [
    { required: true, message: 'Please enter user UID', trigger: 'blur' },
    { type: 'number', min: 1, message: 'UID must be a positive integer', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: 'Please enter recharge amount', trigger: 'blur' },
    { type: 'number', min: 1, max: 100000, message: 'Amount must be between 1-100000', trigger: 'blur' }
  ],
  paymentName: [
    { required: true, message: 'Please enter payer\'s real name', trigger: 'blur' },
    { min: 2, max: 50, message: 'Name length should be between 2-50 characters', trigger: 'blur' }
  ],
  transAccNo: [
    { required: true, message: 'Please enter bank card number', trigger: 'blur' },
    { pattern: /^\d{10,20}$/, message: 'Bank card number must be 10-20 digits', trigger: 'blur' }
  ],
  bankCode: orderForm.value.paymentChannel === 'LSPPAY'
    ? []
    : [
      { required: true, message: 'Please select bank code', trigger: 'change' },
      {
        validator: (rule: any, value: string, callback: Function) => {
          if (!value) {
            callback(new Error('Please select bank code'))
            return
          }

          const channel = orderForm.value.paymentChannel
          if (channel === 'TOPPAY') {
            // TopPay要求数字编码（如001, 003, 004）
            if (!/^\d{3}$/.test(value)) {
              callback(new Error('TopPay bank code must be 3 digits'))
              return
            }
          } else if (channel === 'PAY668') {
            // Pay668使用银行简称（如KBANK, BBL, KTB）
            if (!/^[A-Z]{2,10}$/.test(value)) {
              callback(new Error('Pay668 bank code must be bank abbreviation (e.g., KBANK, BBL)'))
              return
            }
          } else if (channel === 'HUIFENG') {
            if (!/^[A-Za-z0-9]{2,20}$/.test(value)) {
              callback(new Error('Huifeng bank code must be 2-20 letters or digits'))
              return
            }
          } else if (channel === 'NASKI') {
            // NASKI使用银行简称（如BAY, KTB, BBL）
            if (!/^[A-Z]{2,10}$/.test(value)) {
              callback(new Error('NASKI bank code must be bank abbreviation (e.g., BAY, KTB, BBL)'))
              return
            }
          }

          callback()
        },
        trigger: 'change'
      }
    ],
  customerEmail: [
    { type: 'email', message: 'Please enter correct email format', trigger: 'blur' }
  ],
  customerPhone: [
    { pattern: /^[0-9+\-\s()]+$/, message: 'Please enter correct phone format', trigger: 'blur' }
  ],
  extendParam: [
    { max: 100, message: 'Remarks cannot exceed 100 characters', trigger: 'blur' }
  ],
  createdByName: [
    { required: true, message: 'Please enter order creator name', trigger: 'blur' },
    { min: 2, max: 50, message: 'Creator name length should be between 2-50 characters', trigger: 'blur' }
  ]
}))

// 工具
const toast = useToast()

// Load available payment channels
async function loadAvailableChannels() {
  try {
    loading.value = true
    const result = await trpc.recharge.getAvailableChannels.query()

    if (result.success) {
      availableChannels.value = result.data.channels.map((channel: any) => ({
        value: channel.value,
        label: channel.label
      }))
    } else {
      toast.error(result.message || 'Failed to load payment channels')
    }
  } catch (error) {
    console.error('Failed to load channels:', error)
    toast.error('Failed to load payment channels')
  } finally {
    loading.value = false
  }
}

// Handle payment channel change
function handleChannelChange() {
  // Reset bank code when channel changes as different channels may have different bank codes
  orderForm.value.bankCode = ''
  
  // Clear form validation errors for bank code field
  orderFormRef.value?.clearValidate(['bankCode'])
}

// 银行编码选项数据
const topPayBankOptions = [
  { label: 'Kasikorn Bank Plc. (KBANK)', value: '001' },
  { label: 'Bangkok Bank Plc. (BBL)', value: '003' },
  { label: 'Krung Thai Bank (KTB)', value: '004' },
  { label: 'ABN Amro Bank N.V. (ABN)', value: '005' },
  { label: 'TMBThanachart (TTB)', value: '007' },
  { label: 'Siam Commercial Bank (SCB)', value: '010' },
  { label: 'UOB Bank Plc. (UOB)', value: '016' },
  { label: 'Bank of Ayudhya / Krungsri (BAY)', value: '017' },
  { label: 'CIMB Thai Bank Public Company Limited (CIMB)', value: '018' },
  { label: 'Land and Houses Bank Public Company Limited (LHBANK)', value: '020' },
  { label: 'Government Savings Bank (GSB)', value: '022' },
  { label: 'Kiatnakin Phatra Bank Public Company Limited (KKP)', value: '023' },
  { label: 'Citibank N.A. (CITI)', value: '024' },
  { label: 'Government Housing Bank (GHB)', value: '025' },
  { label: 'Bank for Agriculture and Agricultural Cooperatives (BAAC)', value: '026' },
  { label: 'Mizuho Corporate Bank Limited (MHCB)', value: '027' },
  { label: 'Islamic Bank of Thailand (IBANK)', value: '028' },
  { label: 'TISCO Bank Plc. (TISCO)', value: '029' }
]

// NASKI 银行编码选项（根据泰国银行列表）
const naskiBankOptions = [
  { label: 'Bank of Ayudhya (BAY)', value: 'BAY' },
  { label: 'Krung Thai Bank (KTB)', value: 'KTB' },
  { label: 'Bangkok Bank (BBL)', value: 'BBL' },
  { label: 'Siam Commercial Bank (SCB)', value: 'SCB' },
  { label: 'TMB Bank (TMB)', value: 'TMB' },
  { label: 'Thanachart Bank (TBANK)', value: 'TBANK' },
  { label: 'Bank for Agriculture and Agricultural Cooperatives (BAAC)', value: 'BAAC' },
  { label: 'Land and Houses Bank (LHBANK)', value: 'LHBANK' }
]

const pay668BankOptions = [
  { label: 'BANK FOR AGRICULTURE AND AGRICULTURAL CO-OPERATIVES (BAAC)', value: 'BAAC' },
  { label: 'BANK OF AYUDHAYA PUBLIC COMPANY LTD. (BAY)', value: 'BAY' },
  { label: 'BANGKOK BANK PUBLIC COMPANY LTD. (BBL)', value: 'BBL' },
  { label: 'BNP PARIBAS BANGKOK BRANCH (BNPP)', value: 'BNPP' },
  { label: 'BANK OF AMERICA NT&SA (BOA)', value: 'BOA' },
  { label: 'Bank of China (Thai) PCL (BOC)', value: 'BOC' },
  { label: 'BANK OF THAILAND (BOT)', value: 'BOT' },
  { label: 'JPMorgan Chase Bank, Bangkok Branch (CHAS)', value: 'CHAS' },
  { label: 'CIMB THAI BANK PUBLIC COMPANY LTD (CIMB)', value: 'CIMB' },
  { label: 'CITI BANK N.A. (CITI)', value: 'CITI' },
  { label: 'Deutsche Bank AG (DB)', value: 'DB' },
  { label: 'EXPORT–IMPORT BANK OF THAILAND (EXIM)', value: 'EXIM' },
  { label: 'GOVERNMENT HOUSING BANK (GHB)', value: 'GHB' },
  { label: 'THE GOVERNMENT SAVING BANK (GSB)', value: 'GSB' },
  { label: 'THE HONGKONG & SHANGHAI CORPORATION LTD (HSBC)', value: 'HSBC' },
  { label: 'Industrial and Commercial Bank of China (Thai) Public Company Limited (IACBC)', value: 'IACBC' },
  { label: 'INDUSTRIAL AND COMMERCIAL BANK OF CHINA (THAI) PCL (ICBC)', value: 'ICBC' },
  { label: 'INDIAN OVERSEAS BANK (IOB)', value: 'IOB' },
  { label: 'KASIKORNBANK PCL (KBANK)', value: 'KBANK' },
  { label: 'KIATNAKIN BANK PCL (KKP)', value: 'KKP' },
  { label: 'KRUNG THAI BANK PUBLIC COMPANY LTD. (KTB)', value: 'KTB' },
  { label: 'Land and Houses Bank (LHBA)', value: 'LHBA' },
  { label: 'MEGA INTERNATIONAL COMMERCIAL BANK (MEGA)', value: 'MEGA' },
  { label: 'MIZUHO CORPORATE BANK (MHCB)', value: 'MHCB' },
  { label: 'THE SIAM COMMERCIAL BANK PUBLIC COMPANY (SCB)', value: 'SCB' },
  { label: 'STANDARD CHARTERED BANK THAI PCL (SCBT)', value: 'SCBT' },
  { label: 'THE SUMITOMO MITSU BANKING CORPORATION (SMBC)', value: 'SMBC' },
  { label: 'Sumitomo Mitsui Trust Bank (Thai) PCL (SMTB)', value: 'SMTB' },
  { label: 'Thanachart Bank Public Company Limited (TBNK)', value: 'TBNK' },
  { label: 'THE THAI CREDIT RETAIL BANK (TCRB)', value: 'TCRB' },
  { label: 'ISLAMIC BANK OF THAILAND (TIBT)', value: 'TIBT' },
  { label: 'TISCO Bank PCL (TISCO)', value: 'TISCO' },
  { label: 'TMB BANK PUBLIC COMPANY LTD. (TMB)', value: 'TMB' },
  { label: 'TMBThanachart Bank Public Company Limited (TTB)', value: 'TTB' },
  { label: 'UNITED OVERSEAS BANK (THAI) PUBLIC COMPANY LTD. (UOB)', value: 'UOB' },
  { label: 'SME (SME)', value: 'SME' },
  { label: 'IBANK (IBANK)', value: 'IBANK' },
  { label: 'Krungsri (KRU)', value: 'KRU' }
]

const huifengBankOptions = [
  ...topPayBankOptions,
  ...pay668BankOptions
]

// LSPPAY 银行编码选项（主要支持 PromptPay，不需要特定银行编码）
const lspPayBankOptions = [
  { label: 'Not Required - Using PromptPay', value: '' },
]

// Computed properties
const bankOptions = computed(() => {
  if (orderForm.value.paymentChannel === 'TOPPAY') {
    return topPayBankOptions
  } else if (orderForm.value.paymentChannel === 'PAY668') {
    return pay668BankOptions
  } else if (orderForm.value.paymentChannel === 'LSPPAY') {
    return lspPayBankOptions
  } else if (orderForm.value.paymentChannel === 'HUIFENG') {
    return huifengBankOptions
  } else if (orderForm.value.paymentChannel === 'NASKI') {
    return naskiBankOptions
  }
  return [] // 未选择渠道时返回空数组
})


const paymentChannelLabel = computed(() => {
  const labels: Record<string, string> = {
    'TOPPAY': 'TopPay',
    'PAY668': '668Pay',
    'LSPPAY': 'LSPPAY',
    'HUIFENG': '汇沣支付',
    'NASKI': 'NASKI支付'
  }
  return labels[orderForm.value.paymentChannel] || orderForm.value.paymentChannel
})

const paymentMethodLabel = computed(() => {
  const labels: Record<string, string> = {
    'BankTransfer': 'Bank Transfer',
    'qrPay': 'QR Code Payment'
  }
  return labels[orderForm.value.paymentMethod] || orderForm.value.paymentMethod
})

// 银行标签映射
const getBankLabel = (bankCode: string) => {
  const bankLabels: Record<string, string> = {
    'BAAC': 'Bank for Agriculture and Agricultural Co-operatives (BAAC)',
    'BAY': 'Bank of Ayudhya Public Company Ltd. (BAY)',
    'BBL': 'Bangkok Bank Public Company Ltd. (BBL)',
    'BNPP': 'BNP Paribas Bangkok Branch (BNPP)',
    'BOA': 'Bank of America NT&SA (BOA)',
    'BOC': 'Bank of China (Thai) PCL (BOC)',
    'BOT': 'Bank of Thailand (BOT)',
    'CHAS': 'JPMorgan Chase Bank, Bangkok Branch (CHAS)',
    'CIMB': 'CIMB Thai Bank Public Company Ltd (CIMB)',
    'CITI': 'Citi Bank N.A (CITI)',
    'DB': 'Deutsche Bank AG (DB)',
    'EXIM': 'Export–Import Bank of Thailand (EXIM)',
    'GHB': 'Government Housing Bank (GHB)',
    'GSB': 'The Government Savings Bank (GSB)',
    'HSBC': 'The Hongkong & Shanghai Corporation Ltd (HSBC)',
    'IACBC': 'Industrial and Commercial Bank of China (Thai) Public Company Limited (IACBC)',
    'ICBC': 'Industrial and Commercial Bank of China (Thai) PCL (ICBC)',
    'IOB': 'Indian Overseas Bank (IOB)',
    'KBANK': 'Kasikornbank PCL (KBANK)',
    'KKP': 'Kiatnakin Bank PCL (KKP)',
    'KTB': 'Krung Thai Bank Public Company Ltd. (KTB)',
    'LHBA': 'Land and Houses Bank (LHBA)',
    'MEGA': 'Mega International Commercial Bank (MEGA)',
    'MHCB': 'Mizuho Corporate Bank (MHCB)',
    'SCB': 'The Siam Commercial Bank Public Company (SCB)',
    'SCBT': 'Standard Chartered Bank Thai PCL (SCBT)',
    'SMBC': 'The Sumitomo Mitsu Banking Corporation (SMBC)',
    'SMTB': 'Sumitomo Mitsui Trust Bank (Thai) PCL (SMTB)',
    'TBNK': 'Thanachart Bank Public Company Limited (TBNK)',
    'TCRB': 'The Thai Credit Retail Bank (TCRB)',
    'TIBT': 'Islamic Bank of Thailand (TIBT)',
    'TISCO': 'TISCO Bank PCL (TISCO)',
    'TMB': 'TMB Bank Public Company Ltd. (TMB)',
    'TTB': 'TMBThanachart Bank Public Company Limited (TTB)',
    'UOB': 'United Overseas Bank (Thai) Public Company Ltd. (UOB)',
    'SME': 'SME (SME)',
    'IBANK': 'IBANK (IBANK)',
    'KRU': 'Krungsri (KRU)',
    // 保持对旧编码的兼容性
    '001': 'Kasikorn Bank (KBANK)',
    '003': 'Bangkok Bank (BBL)',
    '004': 'Krung Thai Bank (KTB)',
    '005': 'ABN Amro Bank (ABN)',
    '007': 'TMBThanachart (TTB)',
    '010': 'Siam Commercial Bank (SCB)',
    '016': 'UOB Bank (UOB)',
    '017': 'Bank of Ayudhya/Krungsri (BAY)',
    '018': 'CIMB Thai Bank (CIMB)',
    '020': 'Land and Houses Bank (LHBANK)',
    '022': 'Government Savings Bank (GSB)',
    '023': 'Kiatnakin Phatra Bank (KKP)',
    '024': 'Citibank (CITI)',
    '025': 'Government Housing Bank (GHB)',
    '026': 'Bank for Agriculture (BAAC)',
    '027': 'Mizuho Corporate Bank (MHCB)',
    '028': 'Islamic Bank of Thailand (IBANK)',
    '029': 'TISCO Bank (TISCO)'
  }
  return bankLabels[bankCode] || bankCode
}

// Create order
async function handleCreateOrder() {
  if (!orderFormRef.value) return

  try {
    await orderFormRef.value.validate()

    creating.value = true

    const rawBankCode = orderForm.value.bankCode?.trim() ?? ''
    const normalizedBankCode = (() => {
      if (orderForm.value.paymentChannel === 'LSPPAY') {
        return ''
      }
      if (orderForm.value.paymentChannel === 'PAY668' || orderForm.value.paymentChannel === 'HUIFENG' || orderForm.value.paymentChannel === 'NASKI') {
        return rawBankCode.toUpperCase()
      }
      return rawBankCode
    })()

    orderForm.value.bankCode = normalizedBankCode

    const result = await trpc.recharge.create.mutate({
      userId: orderForm.value.userId!,
      amount: orderForm.value.amount!,
      paymentChannel: orderForm.value.paymentChannel as 'TOPPAY' | 'PAY668' | 'LSPPAY' | 'HUIFENG' | 'NASKI',
      paymentMethod: orderForm.value.paymentMethod as 'BankTransfer' | 'qrPay',
      paymentName: orderForm.value.paymentName,
      transAccNo: orderForm.value.transAccNo!, // Required field
      bankCode: normalizedBankCode,
      customerEmail: orderForm.value.customerEmail || undefined,
      customerPhone: orderForm.value.customerPhone || undefined,
      extendParam: orderForm.value.extendParam || undefined,
      createdByName: orderForm.value.createdByName
    })

    if (result.success) {
      toast.success('Recharge order created successfully!')

      // Open payment link in new window if available
      const paymentResponse = result.data.paymentResponse
      if (paymentResponse.payUrl || paymentResponse.qrCodeUrl) {
        const payUrl = paymentResponse.payUrl || paymentResponse.qrCodeUrl
        window.open(payUrl, '_blank')
      }

      handleResetForm()
    } else {
      toast.error(result.message || 'Failed to create order')
    }
  } catch (error) {
    console.error('Failed to create order:', error)
    toast.error('Failed to create order')
  } finally {
    creating.value = false
  }
}

// Reset form
function handleResetForm() {
  orderFormRef.value?.resetFields()
  orderForm.value = {
    paymentChannel: '',
    paymentMethod: '',
    userId: null,
    amount: null,
    transAccNo: '',
    paymentName: '',
    bankCode: '',
    customerEmail: '',
    customerPhone: '',
    extendParam: '',
    createdByName: ''
  }
}

// 页面加载时获取可用支付渠道
onMounted(() => {
  loadAvailableChannels()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
}

.order-preview {
  margin-top: 16px;
}

.empty-preview {
  text-align: center;
  padding: 40px 0;
}


</style>
